

const http = require('http');
const path = require('path');
const url = require('url');
// const fsp = require('fs/promises');
const fs = require('fs');
const fsp = fs.promises;

const { createServer } = http;

// var server = createServer(function (req,res) { });
var server = createServer();

var siteUrl = path.join(__dirname, "../site"); // 默认站点路径 (前端相关的文件 放到site目录中)

server.on("request", function (req, res) {
    console.log(1111);
})
server.on("request", function (req, res) {
    console.log(2222);
    if (req.url != "/favicon.ico") {
        console.log("接收前端发送的请求");
        console.log(req.url);

        var urlInfo = url.parse(req.url, true);
        // console.log(urlInfo);

        var { pathname, query } = urlInfo;


        // 判断 req.url(路径) 在站点中是否存在
        var readPath = path.join(siteUrl, pathname);
        if (fs.existsSync(readPath)) {

            // 如果在站点中存在 -> 取的改文件 -> 传递给前端
            var defaultEncoding = "utf-8";

            var ext = path.extname(readPath);
            console.log(11111, ext);

            var imgExts = [".jpg", ".jpeg", ".png", ".gif", ".webp"];

            if (imgExts.includes(ext)) { //如果是图片格式
                defaultEncoding = "binary";
                if (ext == ".jpg") {
                    res.writeHead(200, {
                        "Content-Type": "image/jpg",
                    })
                } if (ext == ".jpeg") {
                    res.writeHead(200, {
                        "Content-Type": "image/jpeg",
                    })
                } else if (ext == ".png") {
                    res.writeHead(200, {
                        "Content-Type": "image/png",
                    })
                } else if (ext == ".gif") {
                    res.writeHead(200, {
                        "Content-Type": "image/gif",
                    })
                }

            } else if (ext == ".js") {
                res.writeHead(200, {
                    "Content-Type": "text/javascript;charset=utf-8",
                })
            } else if (ext == ".css") {
                res.writeHead(200, {
                    "Content-Type": "text/css;charset=utf-8",
                })
            } else if (ext == ".json") {
                res.writeHead(200, {
                    "Content-Type": "text/json;charset=utf-8",
                })
            }

            // HTML css JS(!!)
            fsp.readFile(readPath, defaultEncoding).then(txt => {
                // res.writeHead(200, {
                //     "Content-Type": "image/png",
                // })
                res.end(txt, defaultEncoding);
            })

        } else {
            res.end("2222");
        }




    } else {
        res.end();
    }
})


server.listen(3000, function () {
    console.log("服务器启动成功localhost:3000");
})

